package ru.amse.tsyganov.jumleditor.view;

import org.eclipse.swt.graphics.GC;

import ru.amse.tsyganov.jumleditor.model.State;
import ru.amse.tsyganov.jumleditor.model.StateVertex;
import ru.amse.tsyganov.jumleditor.model.Transition;

public class TransitionView<T extends Transition> extends View<Transition> {
	
	private StateVertex<TransitionView<T>, StateView<? extends State>> source;
	private StateVertex<TransitionView<T>, StateView<? extends State>> target;
	
	public TransitionView(T model,
			StateVertex<TransitionView<T>, StateView<? extends State>> sourceVertex, 
			StateVertex<TransitionView<T>, StateView<? extends State>> targetVertex) {
		
		if (sourceVertex == null || targetVertex == null ||
				sourceVertex == targetVertex || model == null) {
			throw new IllegalArgumentException();
		}
		
		source = sourceVertex;
		target = targetVertex;
		setModel(model);
		
		sourceVertex.getOutgoing().add(this);
		targetVertex.getIncoming().add(this);
	}
	
	public StateVertex<TransitionView<T>, StateView<? extends State>> getSource() {
		assert source != null;
		return source;
	}

	public void setSource(
			StateVertex<TransitionView<T>, StateView<? extends State>> sourceVertex) {
		
		if (sourceVertex == null) {
			throw new IllegalArgumentException();
		}
		
		assert source.getOutgoing().contains(this);
		
		source.getOutgoing().remove(this);
		source = sourceVertex;
		source.getOutgoing().add(this);
		
		assert source.getOutgoing().contains(this);
	}

	public StateVertex<TransitionView<T>, StateView<? extends State>> getTarget() {
		assert target != null;
		return target;
	}

	public void setTarget(
			StateVertex<TransitionView<T>, StateView<? extends State>> targetVertex) {
		
		if (targetVertex == null) {
			throw new IllegalArgumentException();
		}
		
		assert target.getIncoming().contains(this);
		
		target.getIncoming().remove(this);
		target = targetVertex;
		target.getIncoming().add(this);
		
		assert target.getIncoming().contains(this);
	}
	
	public void delete() {
		target.getIncoming().remove(this);
		source.getOutgoing().remove(this);
	}
	
	public void paint(GC gc) {
		TransitionDraughtsman.drawTransition(gc, this);
	}
}
